#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

import logging

from google.appengine.api import users
from google.appengine.ext import db
import gdata.alt.appengine

from core.gcalendar import Calendar
from gdata.base.service import RequestError
from core.models import CoreUser

def reset_calendar_url(coreuser, title):
    calendar = Calendar(coreuser.token)

    id_cal = calendar._GetID(title)
    if id_cal is None:
        # TODO: timezone!!
        calendar.CreateCalendar(title=title, description='textLocutor! calendar...', time_zone='Spain/Europe', location='Madrid') 

    coreuser.id_calendar = calendar._GetID(title)
    coreuser.put()


def reset_token(request_h):
    coreuser = CoreUser.all().filter('user =', users.get_current_user()).get()
    
    if coreuser:
        token = None
        for param in request_h.request.query_string.split('&'):
            # Get the token scope variable we specified when generating the URL
            if param.startswith('token_scope'):
                token_scope = urllib.unquote_plus(param.split('=')[1])
            # Google Data will return a token, get that
            elif param.startswith('token'):
                token = param.split('=')[1]

        if token:
            gcalendar_service = gdata.service.GDataService()
                #http://groups.google.com/group/google-appengine/msg/de1b140fea4cb351
            gdata.alt.appengine.run_on_appengine(gcalendar_service)
            gcalendar_service.SetAuthSubToken(str(token))
            logging.debug(token)
            gcalendar_service.UpgradeToSessionToken()
            coreuser.token = gcalendar_service.GetAuthSubToken()
            coreuser.put()

            request_h.redirect(request_h.request.host_url)
        else:
            next = '%s/core/reset_token/' % request_h.request.host_url
            scope = 'http://www.google.com/calendar/feeds'
            secure = False
            session = True
            gcalendar_service = gdata.service.GDataService()
            gdata.alt.appengine.run_on_appengine(gcalendar_service)
            url = gcalendar_service.GenerateAuthSubURL(next, scope, secure, session)

            request_h.redirect(url.__str__(), True)    
    else:
        request_h.view('Invalid user')


def send_message(coreuser, message):
    try:
        calendar = Calendar(coreuser.token)
    except Exception, detail:
        logging.error("Error creating calendar object for user %s" % (coreuser.user.nickname()))

    # Max 60 chars. Split the message if longer
    pos = 0
    message_splitted = []
    while pos < len(message):
        message_splitted.append(message[pos:pos+60])
        pos = pos + 60

    for m in message_splitted:
        calendar._InsertEvent(title=m, content='TextLocutor', where=None, start_time=None, end_time=None, id_cal=coreuser.id_calendar)
